#include "gd32f10x_i2c.h"
#include "gd32f10x_rcu.h"
#include "OLED.h"
#define address 0x78
void OLED_WriteData(uint8_t Data)
{
   MyI2C_Start();
   MyI2C_SendByte(address);
   MyI2C_ReceiveAck();
   MyI2C_SendByte(0x40);
   MyI2C_ReceiveAck();
   MyI2C_SendByte(Data);
   MyI2C_ReceiveAck();
   MyI2C_Stop();
}
void OLED_WriteCommand(uint8_t Command)
{
	MyI2C_Start();
	MyI2C_SendByte(address);
	MyI2C_ReceiveAck();
	MyI2C_SendByte(0x00);
	MyI2C_ReceiveAck();
	MyI2C_SendByte(Command);
	MyI2C_ReceiveAck();
	MyI2C_Stop();
}
void OLED_Init()
{
    
	OLED_WriteCommand(0xAE);	
	
	OLED_WriteCommand(0xD5);
	OLED_WriteCommand(0x80);	
	
	OLED_WriteCommand(0xA8);	
	OLED_WriteCommand(0x3F);	
	
	OLED_WriteCommand(0xD3);	
	OLED_WriteCommand(0x00);	
	
	OLED_WriteCommand(0x40);	
	
	OLED_WriteCommand(0xA1);	
	
	OLED_WriteCommand(0xC8);	

	OLED_WriteCommand(0xDA);	
	OLED_WriteCommand(0x12);
	
	OLED_WriteCommand(0x81);
	OLED_WriteCommand(0xCF);	

	OLED_WriteCommand(0xD9);	
	OLED_WriteCommand(0xF1);

	OLED_WriteCommand(0xDB);	
	OLED_WriteCommand(0x30);

	OLED_WriteCommand(0xA4);	

	OLED_WriteCommand(0xA6);	

	OLED_WriteCommand(0x8D);	
	OLED_WriteCommand(0x14);

	OLED_WriteCommand(0xAF);	
}
void OLED_SetCursor(uint8_t page,uint8_t x)
{
	OLED_WriteCommand(0xB0 | page);					
	OLED_WriteCommand(0x10 | ((x & 0xF0) >> 4));	
	OLED_WriteCommand(0x00 | (x & 0x0F));			
}
void OLED_Clear()
{
	uint8_t i,j;
	for(i=0;i<8;i++)
	{
		OLED_SetCursor(i,0);
		for(j=0;j<128;j++)
		{
			
			OLED_WriteData(0x00);
		}
	}
}
uint32_t OLED_Pow(uint8_t m,uint8_t n)
{
	uint32_t result=1;
	while(n--)result*=m;
	return result;
}
void OLED_ShowNum(uint8_t Y,uint8_t X,uint32_t Number,uint8_t Length,uint8_t FontSize)
{
	uint8_t i, SingleNumber;
	for (i = 0; i < Length; i++)		
	{
		SingleNumber = Number / OLED_Pow(10, Length - i - 1) % 10;
		OLED_ShowChar(Y, X + i * FontSize, SingleNumber + '0', FontSize);
	}
}
void OLED_ShowHexNum(uint8_t Y, uint8_t X, uint32_t Number, uint8_t Length, uint8_t FontSize)
{
	uint8_t i, SingleNumber;
	for (i = 0; i < Length; i++)		
	{
		SingleNumber = Number / OLED_Pow(16, Length - i - 1) % 16;
		if (SingleNumber < 10)			
		{
			OLED_ShowChar(Y, X + i * FontSize, SingleNumber + '0', FontSize);
		}
		else
		{			
			OLED_ShowChar(Y, X + i * FontSize, SingleNumber - 10 + 'A', FontSize);
		}
	}
}
void OLED_ShowChar(uint8_t page,uint8_t x,char Char,uint8_t FontSize)
{
	uint8_t i;
	if(FontSize==6)
	{
		OLED_SetCursor(page,x);
		for(i=0;i<6;i++)
		{
			OLED_WriteData(OLED_F6x8[Char-' '][i]);
		}
	}
	if(FontSize==8)
	{
		OLED_SetCursor(page,x);
		for(i=0;i<8;i++)
		{
			OLED_WriteData(OLED_F8x16[Char-' '][i]);
		}
		OLED_SetCursor(page+1,x);
		for(i=0;i<8;i++)
		{
			OLED_WriteData(OLED_F8x16[Char-' '][i+8]);
		}
	}
}
void OLED_ShowString(uint8_t page,uint8_t x,char *String,uint8_t FontSize)
{
	for(uint8_t i=0;String[i]!='\0';i++)
	{
		OLED_ShowChar(page,x+i*FontSize,String[i],FontSize);
		
	}
}